const { v4 : uuidv4 } = require('uuid');
const User = require('./User');
const Room = require('./Room');

class SocketManager {
    constructor(server){
        this.connectUsers = [];
        this.rooms = [];
        this.socket = null;
        this.io = require('socket.io')(server, {
            cors: {
              origin: '*',
              methods: ['GET', 'POST'],
            },
        });
    }

    IOConnection(){
        this.io.on('connection',(socket) => {
            this.socket = socket;
            console.log(`用户已实现socket连接${this.socket.id}`);

            socket.on('create-new-room', (data) => {
                this.createNewRoomHandler(data);
            });

            socket.on('join-room', (data) => {
                this.joinRoomHandler(data);
            });

            socket.on('disconnect', () => {
                
            });

            socket.on('conn-signal', (data) => {
                
            });

            socket.on('conn-init', (data) => {
                
            });
            
            socket.on('direct-message', (data) => {
                
            });
        })
    }

    createNewRoomHandler(data) {
        console.log('主持人正在创建会议房间...');
        console.log(data);
        const { identity, onlyAudio } = data;
        //创建新用户（进入会议的人）
        const roomId = uuidv4();
        const user = new User(identity,uuidv4(),roomId,this.socket.id,onlyAudio);
        //将新用户添加到已连接的用户数组里面
        this.connectedUsers = [...this.connectedUsers, user];
        //创建新会议房间
        const room = new Room(roomId,user);

        this.socket.join(roomId);
        this.rooms = [...this.rooms, room];

        //向客户端发送数据告知会议房间已创建（roomId）
        socket.emit('room-id', { roomId });

        //发送通知告知有新用户加入并更新房间
        socket.emit('room-update', { connectedUsers: room.connectedUsers });
    }

    joinRoomHandler(data) {
        const { roomId, identity, onlyAudio } = data;
        const user = new User(identity,uuidv4(),roomId,this.socket.id,onlyAudio);
        const room = this.rooms.find((room) => room.id === roomId);

        room.connectedUsers = [...room.connectedUsers, user];

        this.socket.join(roomId);

        //将新用户添加到已连接的用户数组里面
        this.connectedUsers = [...this.connectedUsers, user];

        room.connectedUsers.forEach(user => {
            if(user.socketId !== this.socket.id){
                //存储发起对等连接方的socketId信息
                const data = {
                    connUserSocketId: this.socket.id,
                };
                this.io.to(user.socketId).emit('conn-prepare', data);
            }
        });

        //发送通知告知有新用户加入并更新房间
        this.io.to(roomId).emit('room-update', { connectedUsers: room.connectedUsers });
    }

    getRooms() {
        return this.rooms;
    }
}

module.exports = SocketManager;